#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    // 1、创造管道
    int p[2] = {0};
    int n = pipe(p);
    if (n != 0)
    {
        std::cerr << "管道错误" << std::endl;
        return 1;
    }

    // 2、创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        std::cerr << "创建子进程错误" << std::endl;
    }
    //3、进行通信
    //父进程 - 写
    else if(id > 0)
    {
        //关闭读端
        close(p[0]);

        std::string s = "i am father";
        write(p[1],s.c_str(),s.size());

        close(p[1]);
        pid_t rid = waitpid(0,nullptr,0);
        (void)rid;

    }
    //子进程 -读
    else if(id == 0)
    {
        //关闭写端
        close(p[1]);

        //读
        char buff[1024];
        int m = read(p[0],buff,1024);
        buff[m] = 0;
        std::cout<<buff<<std::endl;

        close(p[0]);
        exit(0);
    }

    return 0;
}
